/**
 * 账单导入页面逻辑
 */

// 全局变量
let currentImportId = null;
let currentBooks = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', async () => {
    // 检查登录状态
    if (!API.isLoggedIn()) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }

    // 加载账本列表
    await loadBooks();
    
    // 初始化上传区域
    initUploadArea();
    
    // 加载导入历史
    await loadImportHistory();
});

/**
 * 加载账本列表
 */
async function loadBooks() {
    try {
        const response = await API.get('/books');
        currentBooks = response.data;
        
        const select = document.getElementById('bookId');
        select.innerHTML = '';
        
        if (currentBooks.length === 0) {
            select.innerHTML = '<option value="">请先创建账本</option>';
            return;
        }
        
        currentBooks.forEach(book => {
            const option = document.createElement('option');
            option.value = book.book_id;
            option.textContent = `${book.icon} ${book.book_name}`;
            select.appendChild(option);
        });
        
    } catch (error) {
        console.error('加载账本失败:', error);
        alert('加载账本失败：' + error.message);
    }
}

/**
 * 初始化上传区域
 */
function initUploadArea() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');

    // 点击上传
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择
    fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            uploadFile(file);
        }
    });

    // 拖拽上传
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.remove('dragover');
        
        const file = e.dataTransfer.files[0];
        if (file) {
            uploadFile(file);
        }
    });
}

/**
 * 上传文件
 */
async function uploadFile(file) {
    const platform = document.getElementById('platform').value;
    const bookId = document.getElementById('bookId').value;

    // 验证
    if (!bookId) {
        alert('请选择账本');
        return;
    }

    // 检查文件类型
    const allowedExtensions = ['.csv', '.xls', '.xlsx', '.pdf'];
    const fileExt = file.name.toLowerCase().slice(file.name.lastIndexOf('.'));
    if (!allowedExtensions.includes(fileExt)) {
        alert('只支持 CSV、XLS、XLSX、PDF 格式的文件');
        return;
    }

    // 检查文件大小（10MB）
    if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过10MB');
        return;
    }

    // 显示进度条
    const progressContainer = document.getElementById('progressContainer');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    
    progressContainer.style.display = 'block';
    progressFill.style.width = '10%';
    progressFill.textContent = '10%';
    progressText.textContent = '正在上传...';

    try {
        // 创建FormData
        const formData = new FormData();
        formData.append('file', file);
        formData.append('platform', platform);
        formData.append('book_id', bookId);

        // 更新进度
        progressFill.style.width = '30%';
        progressFill.textContent = '30%';
        progressText.textContent = '正在解析文件...';

        // 发送请求
        const response = await fetch(`${API.baseURL}/import/upload`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: formData
        });

        const result = await response.json();

        if (!response.ok) {
            throw new Error(result.error || result.message || '上传失败');
        }

        // 上传成功
        progressFill.style.width = '100%';
        progressFill.textContent = '100%';
        progressText.textContent = '解析完成！';

        // 显示预览
        showPreview(result.preview, result.import_id, result.total_count);

        // 隐藏进度条
        setTimeout(() => {
            progressContainer.style.display = 'none';
            progressFill.style.width = '0%';
        }, 1000);

    } catch (error) {
        console.error('上传失败:', error);
        alert('上传失败：' + error.message);
        
        // 重置进度条
        progressContainer.style.display = 'none';
        progressFill.style.width = '0%';
    }

    // 清空文件输入
    document.getElementById('fileInput').value = '';
}

/**
 * 显示数据预览
 */
function showPreview(transactions, importId, totalCount) {
    currentImportId = importId;

    const previewContainer = document.getElementById('previewContainer');
    const tbody = document.getElementById('previewTableBody');
    
    tbody.innerHTML = '';
    
    if (!transactions || transactions.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:#999;">暂无数据</td></tr>';
        return;
    }
    
    transactions.forEach(tx => {
        const tr = document.createElement('tr');
        const typeClass = tx.type === 'income' ? 'income' : 'expense';
        const typeText = tx.type === 'income' ? '收入' : '支出';
        const timeStr = new Date(tx.transaction_time).toLocaleString('zh-CN');
        
        tr.innerHTML = `
            <td>${timeStr}</td>
            <td><span class="${typeClass}">${typeText}</span></td>
            <td>${tx.merchant || '-'}</td>
            <td>${tx.description}</td>
            <td class="${typeClass}">¥${tx.amount.toFixed(2)}</td>
        `;
        tbody.appendChild(tr);
    });

    previewContainer.style.display = 'block';
    
    // 滚动到预览区域
    previewContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

/**
 * 确认导入
 */
async function confirmImport() {
    if (!currentImportId) {
        alert('没有待导入的数据');
        return;
    }

    // 显示加载中
    const btn = event.target;
    const originalText = btn.textContent;
    btn.textContent = '导入中...';
    btn.disabled = true;

    try {
        const result = await API.post(`/import/process/${currentImportId}`);
        
        // 显示结果
        const message = `导入完成！\n\n✅ 成功：${result.success_count} 条\n⚠️ 重复：${result.duplicate_count} 条\n❌ 错误：${result.error_count} 条`;
        alert(message);
        
        // 重置状态
        currentImportId = null;
        document.getElementById('previewContainer').style.display = 'none';
        
        // 刷新导入历史
        await loadImportHistory();
        
        // 提示跳转
        if (result.success_count > 0) {
            if (confirm('是否跳转到记录页面查看？')) {
                window.location.href = 'index.html';
            }
        }

    } catch (error) {
        console.error('导入失败:', error);
        alert('导入失败：' + error.message);
    } finally {
        btn.textContent = originalText;
        btn.disabled = false;
    }
}

/**
 * 取消导入
 */
function cancelImport() {
    if (confirm('确定要取消本次导入吗？')) {
        currentImportId = null;
        document.getElementById('previewContainer').style.display = 'none';
    }
}

/**
 * 加载导入历史
 */
async function loadImportHistory() {
    try {
        const response = await API.get('/import/history');
        const records = response.data;
        
        const historyContent = document.getElementById('historyContent');
        
        if (!records || records.length === 0) {
            historyContent.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📋</div>
                    <div>暂无导入记录</div>
                </div>
            `;
            return;
        }
        
        // 创建表格
        const table = document.createElement('table');
        table.className = 'history-table';
        table.innerHTML = `
            <thead>
                <tr>
                    <th>导入时间</th>
                    <th>平台</th>
                    <th>账本</th>
                    <th>总数</th>
                    <th>成功</th>
                    <th>重复</th>
                    <th>错误</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody></tbody>
        `;
        
        const tbody = table.querySelector('tbody');
        
        records.forEach(record => {
            const tr = document.createElement('tr');
            
            // 平台名称
            const platformName = {
                'wechat': '微信',
                'alipay': '支付宝',
                'bank': '银行卡'
            }[record.platform] || record.platform;
            
            // 状态样式
            const statusClass = {
                'completed': 'status-completed',
                'processing': 'status-processing',
                'failed': 'status-failed'
            }[record.status] || '';
            
            const statusText = {
                'completed': '已完成',
                'processing': '处理中',
                'failed': '失败'
            }[record.status] || record.status;
            
            const importTime = new Date(record.import_time).toLocaleString('zh-CN');
            
            tr.innerHTML = `
                <td>${importTime}</td>
                <td>${platformName}</td>
                <td>${record.book_name}</td>
                <td>${record.total_count}</td>
                <td style="color: #4CAF50">${record.success_count}</td>
                <td style="color: #ff9800">${record.duplicate_count}</td>
                <td style="color: #f44336">${record.error_count}</td>
                <td><span class="status-badge ${statusClass}">${statusText}</span></td>
            `;
            
            tbody.appendChild(tr);
        });
        
        historyContent.innerHTML = '';
        historyContent.appendChild(table);
        
    } catch (error) {
        console.error('加载导入历史失败:', error);
    }
}

